package cn.xjt.gaoji;

/**
 * @author xujiangtao
 * @create 2020-08-02-12:19
 */
public class Test管程法 {
    public static void main(String[] args) {
        Syncontainer2 container = new Syncontainer2();
        new Producer(container).start();
        new Consumer2(container).start();
    }
}
//生产者
class Producer extends Thread{
    Syncontainer2 container2;
    public Producer(Syncontainer2 container2)
    {
        this.container2=container2;
    }

    @Override
    public void run() {
        for (int i=0;i<10;i++)
        {
            try {
                container2.push(new Chicken2(i));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("生产了"+(i+1)+"只鸡");
        }
    }
}
//消费者
class Consumer2 extends Thread{
    Syncontainer2 container2;
    public Consumer2(Syncontainer2 container2)
    {
        this.container2=container2;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println("消费了第"+(container2.pop().id+1)+"只鸡");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//产品
class Chicken2
{
    int id;
    Chicken2(int id)
    {
        this.id=id;
    }
}
//缓存区
class Syncontainer2{
    //定义了一个容器
    Chicken2[] chicken2s = new Chicken2[10];
    int count=0;
    //生产方法
    public synchronized void push(Chicken2 chicken) throws InterruptedException {
        //如果容器满了
        if(count==chicken2s.length)
        {
            this.wait();
        }
        chicken2s[count] = chicken;
        count++;
        this.notifyAll();   //生产了一个，通知消费者购买
    }
    //消费方法
    public synchronized Chicken2 pop() throws InterruptedException {
        //如果产品没有了，则需要等待
        if(count==0)
        {
            this.wait();
        }
        count--;
//        this.notifyAll();
        return chicken2s[count];
    }
}
